package com.blb.educourseservice.listener;

import com.alibaba.fastjson.JSON;
import com.alibaba.otter.canal.protocol.CanalEntry;
import com.blb.common.config.RabbitMQConfig;
import com.blb.common.entity.Course;
import com.blb.common.entity.ResponseResult;
import com.blb.educourseservice.service.CourseService;
import com.xpand.starter.canal.annotation.CanalEventListener;
import com.xpand.starter.canal.annotation.ListenPoint;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import javax.annotation.Resource;
import java.util.UUID;

/**
 * 课程表Canal监听
 */
@Slf4j
@CanalEventListener
public class CourseCanalListener {

    @Resource
    private RabbitTemplate rabbitTemplate;

    @Resource
    private CourseService courseService;

    /**
     * 指定监听的数据库和表
     * @param eventType
     * @param rowData
     */
    @ListenPoint(schema = "edu_course",table = "course")
    public void updateCourse(CanalEntry.EventType eventType, CanalEntry.RowData rowData){
        String type = eventType.name();
        log.info("操作类型：{}", type);
        if("INSERT".equals(type) || "UPDATE".equals(type)){
            //如果是添加或更新就发送到保存课程队列
            rowData.getAfterColumnsList().forEach(column -> {
                //遍历所有修改后的字段，读取id字段
                if("id".equals(column.getName())){
                    Long id = Long.valueOf(column.getValue());
                    //查询课程相关的数据
                    Course course = courseService.getCourseById(id);
                    //转换为JSON数据
                    String json = JSON.toJSONString(course);
                    //发送给保存课程队列 给消息添加唯一标识
                    rabbitTemplate.convertAndSend(RabbitMQConfig.COURSE_EXCHANGE,
                            RabbitMQConfig.COURSE_SAVE_KEY,json,new CorrelationData(UUID.randomUUID().toString()));
                    log.info("发送保存课程：{}",json);
                }
            });
        }else if("DELETE".equals(type)){
            //如果是删除发送给删除课程队列
            rowData.getBeforeColumnsList().forEach(column -> {
                if("id".equals(column.getName())){
                    Long id = Long.valueOf(column.getValue());
                    //发送给删除课程队列
                    rabbitTemplate.convertAndSend(RabbitMQConfig.COURSE_EXCHANGE,
                            RabbitMQConfig.COURSE_REMOVE_KEY,id,new CorrelationData(UUID.randomUUID().toString()));
                    log.info("发送删除课程：{}",id);
                }
            });
        }
    }
}
